import { reactive, ref, watch } from "vue"
import { pinia } from "@/store"
import { defineStore } from "pinia"
import { getSidebarStatus, setSidebarStatus } from "@/utils/cache/local-storage"
import { DeviceEnum, SIDEBAR_OPENED, SIDEBAR_CLOSED } from "@/constants/app-key"
import { AccReqItem, OpcRealItem, SysLog } from "@/api/acc/types/acc";
import {
  writeOpcListApi,
  saveSysLoglistApi,
  getAccApi,
  getInitApi,
} from "@/api/acc"

interface Sidebar {
  opened: boolean
  withoutAnimation: boolean
}

/** 设置侧边栏状态本地缓存 */
function handleSidebarStatus(opened: boolean) {
  opened ? setSidebarStatus(SIDEBAR_OPENED) : setSidebarStatus(SIDEBAR_CLOSED)
}

export const useAppStore = defineStore("app", () => {
  /** 侧边栏状态 */
  const sidebar: Sidebar = reactive({
    opened: getSidebarStatus() !== SIDEBAR_CLOSED,
    withoutAnimation: false
  })

  const accRunning = ref(false)

  const accConfig = reactive<AccReqItem>({
    steam_flow_SV_range: [40, 60],
    steam_flow_PV: [45],
    air_preheater_temperature_PV: [121.1886, 99.79138],
    steam_header_temperature_SV_range: [0, 0],
    steam_header_temperature_PV: [412],
    incinerator_temperature_SV_range: [0, 0],
    incinerator_temperature_PV: [
      954.9794, 1010.903, 972.7686, 1007.796, 1068.305, 1068.305, 1060.663, 1113.705, 1064.095
    ],
    incinerator_oxygen_content_SV_range: [0, 0],
    incinerator_oxygen_content_PV: [4.949416, 5.012589],
    incinerator_pressure_SV_range: [0, 0],
    incinerator_pressure_PV: [0, 0],
    backward_grate_wind_pressure_PV: [0, 851, 1000, 978, 752, 972, 955, 819, 705, 904, 924, 797, 628, 713, 959, 994],
    forward_grate_wind_pressure_PV: [256, 269, 3, 166],

  })


  /** 设备类型 */
  const device = ref<DeviceEnum>(DeviceEnum.Desktop)

  /** 监听侧边栏 opened 状态 */
  watch(
    () => sidebar.opened,
    (opened) => handleSidebarStatus(opened)
  )

  /** 切换侧边栏 */
  const toggleSidebar = (withoutAnimation: boolean) => {
    sidebar.opened = !sidebar.opened
    sidebar.withoutAnimation = withoutAnimation
  }
  /** 关闭侧边栏 */
  const closeSidebar = (withoutAnimation: boolean) => {
    sidebar.opened = false
    sidebar.withoutAnimation = withoutAnimation
  }
  /** 切换设备类型 */
  const toggleDevice = (value: DeviceEnum) => {
    device.value = value
  }

  const toggleAccStat = ()=>{
    accRunning.value = !accRunning.value
    return Promise.resolve()
  }

  const reWriteConfig=(values:OpcRealItem)=>{
    Object.keys(values).forEach((key) => {
      if (accConfig.hasOwnProperty(key)) {
        // @ts-ignore
        accConfig[key as keyof typeof accConfig] = values[key as keyof typeof values]
      }
    })
  }

  //加载acc范围配置
  const loadConfig = async ()=> {
    const response: any = await getInitApi()
    if (response.code == 0) {
      accConfig.steam_flow_SV_range[0] = response.data.steam_flow_SV_range_min
      accConfig.steam_flow_SV_range[1] = response.data.steam_flow_SV_range_max

      accConfig.steam_header_temperature_SV_range[0] = response.data.steam_header_temperature_SV_range_min
      accConfig.steam_header_temperature_SV_range[1] = response.data.steam_header_temperature_SV_range_max

      accConfig.incinerator_temperature_SV_range[0] = response.data.incinerator_temperature_SV_range_min
      accConfig.incinerator_temperature_SV_range[1] = response.data.incinerator_temperature_SV_range_max

      accConfig.incinerator_oxygen_content_SV_range[0] = response.data.incinerator_oxygen_content_SV_range_min
      accConfig.incinerator_oxygen_content_SV_range[1] = response.data.incinerator_oxygen_content_SV_range_max

      accConfig.incinerator_pressure_SV_range[0] = response.data.incinerator_pressure_SV_range_min
      accConfig.incinerator_pressure_SV_range[1] = response.data.incinerator_pressure_SV_range_max
    }
  }

  const runConfigLoop = async ()=>{
    await loadConfig()
    const accApiData:any = await getAccApi(accConfig)
    let syslogs: Array<SysLog> = []
      // alert告警信息
    if (accApiData.manual_intervention_txt_list.length > 0) {
      let accalertmsg = accApiData.alert_txt_list.join(" | ")
      syslogs.push({
        id: null,
        message: accalertmsg,
        type: 1,
        createtime: new Date()
      })
    }

    if (accApiData.manual_intervention_txt_list.length > 0) {
      // 告警信息
      let accmanualmsg = accApiData.manual_intervention_txt_list.join(" | ")
      syslogs.push({
        id: null,
        message: accmanualmsg,
        type: 1,
        createtime: new Date()
      })
    }

    //返回处理预测写入的opc
    if (accApiData.predict_results_dict != null) {
      // 写入opc告警值
      const writeopcrsp = accApiData.predict_results_dict

      // 存储键值对字符串的数组
      const writeopckvp = []

      for (const key in writeopcrsp) {
        if (accApiData.predict_results_dict.hasOwnProperty(key)) {
          // 动态访问属性，并拼接成字符串
          //  writeopckvp.push(`${key}: ${writeopcrsp[key]}`)
          writeopckvp.push({
            key: key,
            value: writeopcrsp[key]
          })
        }
      }

      // 写入OPC值
      await writeOpcListApi(writeopckvp)

      let writopcmsg = writeopckvp.map((m) => m.key + ":" + m.value).join(" | ")
      syslogs.push({
        id: null,
        message: "正在写入opc值: " + writopcmsg,
        type: 1,
        createtime: new Date()
      })
    }

    await saveSysLoglistApi(syslogs)
    return Promise.resolve()
  }

  return { device, sidebar, toggleSidebar, closeSidebar, toggleDevice,accRunning,toggleAccStat,accConfig,runConfigLoop,reWriteConfig }
})

/**
 * 在 SPA 应用中可用于在 pinia 实例被激活前使用 store
 * 在 SSR 应用中可用于在 setup 外使用 store
 */
export function useAppStoreHook() {
  return useAppStore(pinia)
}
